<template>
  <div class="coupons-page">
    <div class="page-header">
      <h2 class="page-title">优惠券中心</h2>
      <div class="header-actions">
        <el-button 
          v-if="isAdmin" 
          type="primary" 
          @click="showCreateDialog = true"
          v-admin
        >
          <el-icon><Plus /></el-icon>
          创建优惠券
        </el-button>
      </div>
    </div>

    <!-- 优惠券标签页 -->
    <el-tabs v-model="activeTab" @tab-change="handleTabChange">
      <el-tab-pane label="可领取" name="available">
        <div class="coupons-grid">
          <div 
            v-for="coupon in availableCoupons" 
            :key="coupon.id"
            class="coupon-card"
            :class="{ 'limited': coupon.remaining_count > 0 && coupon.remaining_count < 10 }"
          >
            <div class="coupon-header">
              <div class="coupon-value">
                <span class="symbol">¥</span>
                <span class="amount">{{ coupon.value }}</span>
              </div>
              <div class="coupon-type">
                {{ getCouponTypeText(coupon.type) }}
              </div>
            </div>
            
            <div class="coupon-body">
              <h3 class="coupon-name">{{ coupon.name }}</h3>
              <p class="coupon-desc">{{ coupon.description }}</p>
              
              <div class="coupon-rules">
                <span v-if="coupon.min_amount > 0">
                  满{{ coupon.min_amount }}元可用
                </span>
                <span v-if="coupon.max_discount">
                  最高优惠{{ coupon.max_discount }}元
                </span>
              </div>
              
              <div class="coupon-validity">
                有效期至：{{ formatDate(coupon.end_date) }}
              </div>
              
              <div class="coupon-stock" v-if="coupon.total_count > 0">
                剩余：{{ coupon.remaining_count }}张
              </div>
            </div>
            
            <div class="coupon-footer">
              <el-button 
                type="primary" 
                @click="claimCoupon(coupon.id)"
                :loading="claiming === coupon.id"
                :disabled="coupon.remaining_count === 0"
              >
                {{ coupon.remaining_count === 0 ? '已抢完' : '立即领取' }}
              </el-button>
            </div>
          </div>
        </div>
        
        <el-empty v-if="availableCoupons.length === 0" description="暂无可领取的优惠券" />
      </el-tab-pane>

      <el-tab-pane label="我的优惠券" name="my">
        <el-tabs v-model="myActiveTab" type="card">
          <el-tab-pane label="未使用" name="unused">
            <div class="my-coupons-list">
              <div 
                v-for="coupon in myCoupons.unused" 
                :key="coupon.id"
                class="my-coupon-item"
              >
                <div class="coupon-info">
                  <div class="coupon-value-small">
                    ¥{{ coupon.value }}
                  </div>
                  <div class="coupon-details">
                    <h4>{{ coupon.name }}</h4>
                    <p>{{ coupon.description }}</p>
                    <div class="coupon-code">券码：{{ coupon.coupon_code }}</div>
                    <div class="expiry">有效期至：{{ formatDate(coupon.expired_at) }}</div>
                  </div>
                </div>
                <div class="coupon-actions">
                  <el-button type="primary" size="small">立即使用</el-button>
                </div>
              </div>
            </div>
            <el-empty v-if="myCoupons.unused.length === 0" description="暂无未使用的优惠券" />
          </el-tab-pane>
          
          <el-tab-pane label="已使用" name="used">
            <div class="my-coupons-list">
              <div 
                v-for="coupon in myCoupons.used" 
                :key="coupon.id"
                class="my-coupon-item used"
              >
                <div class="coupon-info">
                  <div class="coupon-value-small">
                    ¥{{ coupon.value }}
                  </div>
                  <div class="coupon-details">
                    <h4>{{ coupon.name }}</h4>
                    <p>{{ coupon.description }}</p>
                    <div class="used-info">使用时间：{{ formatDate(coupon.used_at) }}</div>
                  </div>
                </div>
                <div class="used-badge">已使用</div>
              </div>
            </div>
            <el-empty v-if="myCoupons.used.length === 0" description="暂无已使用的优惠券" />
          </el-tab-pane>
          
          <el-tab-pane label="已过期" name="expired">
            <div class="my-coupons-list">
              <div 
                v-for="coupon in myCoupons.expired" 
                :key="coupon.id"
                class="my-coupon-item expired"
              >
                <div class="coupon-info">
                  <div class="coupon-value-small">
                    ¥{{ coupon.value }}
                  </div>
                  <div class="coupon-details">
                    <h4>{{ coupon.name }}</h4>
                    <p>{{ coupon.description }}</p>
                    <div class="expired-info">过期时间：{{ formatDate(coupon.expired_at) }}</div>
                  </div>
                </div>
                <div class="expired-badge">已过期</div>
              </div>
            </div>
            <el-empty v-if="myCoupons.expired.length === 0" description="暂无过期的优惠券" />
          </el-tab-pane>
        </el-tabs>
      </el-tab-pane>
    </el-tabs>

    <!-- 创建优惠券对话框 -->
    <el-dialog
      v-model="showCreateDialog"
      title="创建优惠券"
      width="600px"
      @close="resetCreateForm"
    >
      <el-form
        ref="createFormRef"
        :model="createForm"
        :rules="createRules"
        label-width="100px"
      >
        <el-form-item label="优惠券名称" prop="name">
          <el-input v-model="createForm.name" placeholder="请输入优惠券名称" />
        </el-form-item>
        
        <el-form-item label="描述" prop="description">
          <el-input 
            v-model="createForm.description" 
            type="textarea" 
            placeholder="请输入优惠券描述"
            :rows="3"
          />
        </el-form-item>
        
        <el-form-item label="优惠券类型" prop="type">
          <el-select v-model="createForm.type" placeholder="请选择类型">
            <el-option label="现金券" value="cash" />
            <el-option label="折扣券" value="discount" />
            <el-option label="新用户券" value="newuser" />
            <el-option label="生日券" value="birthday" />
          </el-select>
        </el-form-item>
        
        <el-form-item label="面值" prop="value">
          <el-input-number 
            v-model="createForm.value" 
            :min="0.01" 
            :precision="2"
            placeholder="请输入面值"
          />
          <span class="form-tip">
            {{ createForm.type === 'discount' ? '折扣百分比' : '现金金额' }}
          </span>
        </el-form-item>
        
        <el-form-item label="最低消费" prop="min_amount">
          <el-input-number 
            v-model="createForm.min_amount" 
            :min="0" 
            :precision="2"
            placeholder="最低消费金额"
          />
        </el-form-item>
        
        <el-form-item 
          v-if="createForm.type === 'discount'" 
          label="最高优惠" 
          prop="max_discount"
        >
          <el-input-number 
            v-model="createForm.max_discount" 
            :min="0" 
            :precision="2"
            placeholder="最高优惠金额"
          />
        </el-form-item>
        
        <el-form-item label="有效期" prop="dateRange">
          <el-date-picker
            v-model="createForm.dateRange"
            type="datetimerange"
            range-separator="至"
            start-placeholder="开始时间"
            end-placeholder="结束时间"
            format="YYYY-MM-DD HH:mm:ss"
            value-format="YYYY-MM-DD HH:mm:ss"
          />
        </el-form-item>
        
        <el-form-item label="发放数量" prop="total_count">
          <el-input-number 
            v-model="createForm.total_count" 
            :min="0"
            placeholder="0表示不限制"
          />
        </el-form-item>
        
        <el-form-item label="每人限领" prop="per_user_limit">
          <el-input-number 
            v-model="createForm.per_user_limit" 
            :min="1"
            placeholder="每人限领数量"
          />
        </el-form-item>
      </el-form>
      
      <template #footer>
        <el-button @click="showCreateDialog = false">取消</el-button>
        <el-button 
          type="primary" 
          @click="handleCreateCoupon"
          :loading="creating"
        >
          创建
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue'
import { ElMessage } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import {
  getAvailableCouponsApi,
  claimCouponApi,
  getMyCouponsApi,
  createCouponApi,
  testMarketingApi
} from '@/utils/api'
import { isAdmin } from '@/utils/auth'

// 响应式数据
const activeTab = ref('available')
const myActiveTab = ref('unused')
const availableCoupons = ref([])
const myCoupons = reactive({
  unused: [],
  used: [],
  expired: []
})
const claiming = ref(null)
const loading = ref(false)

// 创建优惠券相关
const showCreateDialog = ref(false)
const creating = ref(false)
const createFormRef = ref()
const createForm = reactive({
  name: '',
  description: '',
  type: 'cash',
  value: 0,
  min_amount: 0,
  max_discount: null,
  dateRange: [],
  total_count: 0,
  per_user_limit: 1
})

const createRules = {
  name: [{ required: true, message: '请输入优惠券名称', trigger: 'blur' }],
  type: [{ required: true, message: '请选择优惠券类型', trigger: 'change' }],
  value: [{ required: true, message: '请输入面值', trigger: 'blur' }],
  dateRange: [{ required: true, message: '请选择有效期', trigger: 'change' }]
}

// 计算属性
const isAdminUser = computed(() => isAdmin())

// 方法
const loadAvailableCoupons = async () => {
  try {
    loading.value = true
    const res = await getAvailableCouponsApi()
    if (res.code === 200) {
      availableCoupons.value = res.data || []
    }
  } catch (error) {
    console.error('获取可用优惠券失败:', error)
    ElMessage.error('获取可用优惠券失败')
  } finally {
    loading.value = false
  }
}

const loadMyCoupons = async () => {
  try {
    const [unusedRes, usedRes, expiredRes] = await Promise.all([
      getMyCouponsApi('unused'),
      getMyCouponsApi('used'),
      getMyCouponsApi('expired')
    ])
    
    myCoupons.unused = unusedRes.data || []
    myCoupons.used = usedRes.data || []
    myCoupons.expired = expiredRes.data || []
  } catch (error) {
    console.error('获取我的优惠券失败:', error)
    ElMessage.error('获取我的优惠券失败')
  }
}

const claimCoupon = async (couponId) => {
  try {
    claiming.value = couponId
    const res = await claimCouponApi(couponId)
    if (res.code === 200) {
      ElMessage.success('优惠券领取成功！')
      await loadAvailableCoupons()
      await loadMyCoupons()
    }
  } catch (error) {
    console.error('领取优惠券失败:', error)
    ElMessage.error(error.response?.data?.message || '领取优惠券失败')
  } finally {
    claiming.value = null
  }
}

const handleTabChange = (tabName) => {
  if (tabName === 'available') {
    loadAvailableCoupons()
  } else if (tabName === 'my') {
    loadMyCoupons()
  }
}

const handleCreateCoupon = async () => {
  try {
    const valid = await createFormRef.value.validate()
    if (!valid) return
    
    creating.value = true
    
    const couponData = {
      ...createForm,
      start_date: createForm.dateRange[0],
      end_date: createForm.dateRange[1]
    }
    delete couponData.dateRange
    
    const res = await createCouponApi(couponData)
    if (res.code === 200) {
      ElMessage.success('优惠券创建成功！')
      showCreateDialog.value = false
      await loadAvailableCoupons()
    }
  } catch (error) {
    console.error('创建优惠券失败:', error)
    ElMessage.error(error.response?.data?.message || '创建优惠券失败')
  } finally {
    creating.value = false
  }
}

const resetCreateForm = () => {
  Object.assign(createForm, {
    name: '',
    description: '',
    type: 'cash',
    value: 0,
    min_amount: 0,
    max_discount: null,
    dateRange: [],
    total_count: 0,
    per_user_limit: 1
  })
  createFormRef.value?.clearValidate()
}

const getCouponTypeText = (type) => {
  const typeMap = {
    cash: '现金券',
    discount: '折扣券',
    newuser: '新用户券',
    birthday: '生日券'
  }
  return typeMap[type] || '优惠券'
}

const formatDate = (dateStr) => {
  return new Date(dateStr).toLocaleDateString('zh-CN')
}

// 测试营销路由
const testMarketingRoute = async () => {
  try {
    const res = await testMarketingApi()
    console.log('营销路由测试结果:', res)
    ElMessage.success('营销路由连接成功！')
  } catch (error) {
    console.error('营销路由测试失败:', error)
    ElMessage.error('营销路由连接失败')
  }
}

// 生命周期
onMounted(() => {
  testMarketingRoute() // 先测试路由
  loadAvailableCoupons()
})
</script>

<style lang="less" scoped>
.coupons-page {
  padding: 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.page-title {
  margin: 0;
  color: #333;
}

.coupons-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
  gap: 20px;
  margin-bottom: 20px;
}

.coupon-card {
  border: 2px solid #f0f0f0;
  border-radius: 12px;
  padding: 20px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  cursor: pointer;
  transition: all 0.3s ease;

  &:hover {
    transform: translateY(-5px);
    box-shadow: 0 10px 25px rgba(0, 0, 0, 0.15);
  }

  &.limited {
    border-color: #ff6b6b;
    animation: pulse 2s infinite;
  }
}

.coupon-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
}

.coupon-value {
  display: flex;
  align-items: baseline;

  .symbol {
    font-size: 18px;
    margin-right: 2px;
  }

  .amount {
    font-size: 32px;
    font-weight: bold;
  }
}

.coupon-type {
  background: rgba(255, 255, 255, 0.2);
  padding: 4px 8px;
  border-radius: 12px;
  font-size: 12px;
}

.coupon-name {
  font-size: 18px;
  margin: 0 0 8px 0;
}

.coupon-desc {
  font-size: 14px;
  opacity: 0.9;
  margin: 0 0 10px 0;
}

.coupon-rules, .coupon-validity, .coupon-stock {
  font-size: 12px;
  opacity: 0.8;
  margin-bottom: 5px;
}

.coupon-footer {
  margin-top: 15px;

  .el-button {
    width: 100%;
    background: rgba(255, 255, 255, 0.2);
    border: 1px solid rgba(255, 255, 255, 0.3);
    color: white;

    &:hover {
      background: rgba(255, 255, 255, 0.3);
    }
  }
}

.my-coupons-list {
  display: flex;
  flex-direction: column;
  gap: 15px;
}

.my-coupon-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 15px;
  border: 1px solid #e8e8e8;
  border-radius: 8px;
  background: white;

  &.used, &.expired {
    opacity: 0.6;
    background: #f9f9f9;
  }
}

.coupon-info {
  display: flex;
  align-items: center;
  gap: 15px;
}

.coupon-value-small {
  font-size: 20px;
  font-weight: bold;
  color: #667eea;
  min-width: 60px;
}

.coupon-details {
  h4 {
    margin: 0 0 5px 0;
    color: #333;
  }

  p {
    margin: 0 0 5px 0;
    color: #666;
    font-size: 14px;
  }

  .coupon-code, .expiry, .used-info, .expired-info {
    font-size: 12px;
    color: #999;
  }
}

.used-badge, .expired-badge {
  padding: 4px 12px;
  border-radius: 12px;
  font-size: 12px;
  font-weight: bold;
}

.used-badge {
  background: #e8f5e8;
  color: #52c41a;
}

.expired-badge {
  background: #fff2f0;
  color: #ff4d4f;
}

.form-tip {
  margin-left: 10px;
  font-size: 12px;
  color: #999;
}

@keyframes pulse {
  0% { border-color: #ff6b6b; }
  50% { border-color: #ff9999; }
  100% { border-color: #ff6b6b; }
}

@media (max-width: 768px) {
  .coupons-grid {
    grid-template-columns: 1fr;
  }

  .page-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 10px;
  }
}
</style>
